from datetime import datetime
from app.models import db


class BaseModel(db.Model):
    """基础模型类，所有模型的父类"""

    __abstract__ = True  # 抽象类，不会被创建为表

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    updated_at = db.Column(
        db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False
    )
    is_active = db.Column(db.Boolean, default=True, nullable=False)

    def to_dict(self):
        """通过类属性直接获取字段"""
        result = {}

        # 获取所有数据库字段
        for column in self.__table__.columns:
            value = getattr(self, column.name)

            # 处理 datetime 对象
            if isinstance(value, datetime):
                value = value.isoformat()

            result[column.name] = value

        return result

    def save(self):
        """保存模型实例"""
        try:
            db.session.add(self)
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            from app.utils.logger import logger

            logger.error(f"保存模型失败: {str(e)}")
            return False

    def delete(self):
        """删除模型实例（逻辑删除）"""
        self.is_active = False
        self.updated_at = datetime.utcnow()
        return self.save()
